package com.huoniu.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.huoniu.common.core.Result;
import com.huoniu.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

import static com.huoniu.api.constrant.GlobalConstrant.TOKEN_PASSWORD;

/**
 * @类 名： LoginInterceptor <br/>
 * @描 述： <br/>
 * @日 期： 2020/9/3 14:02<br/>
 * @作 者： 侯建军<br/>
 * @版 本： 1.0.0
 * @since JDK 1.8
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println(request.getContextPath());
//        System.out.println(request.getRequestURI());
//        System.out.println(request.getRequestURI().contains("login"));
//        Enumeration<String> enumeration = request.getHeaderNames();
//        while (enumeration.hasMoreElements()) {
//            log.info(enumeration.nextElement());
//        }
//        String value = request.getHeader("token");
//        log.info(value);
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");
        log.info(request.getRequestURI());
        if (!StringUtils.isEmpty(token)) {
            String username = JwtUtils.getUsername(token);
            if (JwtUtils.verify(token, username, TOKEN_PASSWORD)) {
                return true;
            }
        }
        Result result=Result.fail("token不正确，请登录");
        result.setCode("5555");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(result));
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
